package demo.db.hbase;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.hbase.thrift2.generated.TColumnValue;
import org.apache.hadoop.hbase.thrift2.generated.TGet;
import org.apache.hadoop.hbase.thrift2.generated.THBaseService;
import org.apache.hadoop.hbase.thrift2.generated.TIOError;
import org.apache.hadoop.hbase.thrift2.generated.TPut;
import org.apache.hadoop.hbase.thrift2.generated.TResult;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Thrift2Demo {

    private static final Logger logger = LoggerFactory.getLogger(Thrift2Demo.class);

    public static void main(String[] args) throws TIOError, TException {
        logger.info("hello");
        String host = "172.17.16.61";
        int port = 9090;

        int timeout = 10000;
        boolean framed = true;

        TTransport transport = new TSocket(host, port, timeout);
        if (framed) {
            transport = new TFramedTransport(transport);
        }
        TProtocol protocol = new TBinaryProtocol(transport);
        // This is our thrift client.
        THBaseService.Iface client = new THBaseService.Client(protocol);

        // open the transport
        transport.open();

        ByteBuffer table = ByteBuffer.wrap("t1".getBytes());

        /*TPut put = new TPut();
        put.setRow("103".getBytes());

        TColumnValue columnValue = new TColumnValue();
        columnValue.setFamily("cf1".getBytes());
        columnValue.setQualifier("title".getBytes());
        columnValue.setValue("change thirft".getBytes());
        List<TColumnValue> columnValues = new ArrayList<TColumnValue>();
        columnValues.add(columnValue);
        put.setColumnValues(columnValues);

        client.put(table, put);*/

        TGet get = new TGet();
        get.setRow("103".getBytes());

        TResult result = client.get(table, get);

        System.out.print("row = " + new String(result.getRow()));
        for (TColumnValue resultColumnValue : result.getColumnValues()) {
            System.out.print(",family = " + new String(resultColumnValue.getFamily()));
            System.out.print(",qualifier = " + new String(resultColumnValue.getFamily()));
            System.out.print(",value = " + new String(resultColumnValue.getValue()));
            System.out.print(",timestamp = " + resultColumnValue.getTimestamp());
        }

        transport.close();
    }

}
